<template>
  <div class="order-create">
    <PageHeader title="创建订单" />

    <!-- 收货地址 -->
    <div class="address-card" @click="goToSelectAddress">
      <div v-if="selectedAddress" class="address-info">
        <div class="receiver">
          <span class="name">{{ selectedAddress.name }}</span>
          <span class="phone">{{ selectedAddress.phone }}</span>
        </div>
        <div
          class="address"
        >{{ selectedAddress.province + selectedAddress.city + selectedAddress.district + selectedAddress.detail }}</div>
      </div>
      <div v-else class="address-empty">
        <span>请选择收货地址</span>
      </div>
      <van-icon name="arrow" class="right-icon" />
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <div class="section-title">商品清单</div>
      <div class="product-item" v-for="item in products" :key="item.id">
        <img :src="item.image" :alt="item.name" class="product-img" />
        <div class="product-info">
          <div class="product-name">{{ item.name }}</div>
          <div v-if="item.skuSpecs" class="product-specs">
            <span v-for="(value, key) in item.skuSpecs" :key="key">{{ key }}: {{ value }}</span>
          </div>
          <div class="product-price">{{ item.price }} 积分</div>
          <div class="product-quantity">x{{ item.quantity }}</div>
        </div>
      </div>
    </div>

    <!-- 订单备注 -->
    <div class="remark-card">
      <div class="section-title">订单备注</div>
      <van-field v-model="remark" type="textarea" placeholder="请输入订单备注" rows="2" autosize />
    </div>

    <!-- 订单信息 -->
    <div class="order-info">
      <div class="order-item">
        <span>商品件数</span>
        <span>{{ totalQuantity }}件</span>
      </div>
      <div class="order-item">
        <span>消耗积分</span>
        <span class="price">{{ totalAmount }}积分</span>
      </div>
    </div>

    <!-- 提交订单 -->
    <div class="submit-bar">
      <div class="total">
        合计：
        <span class="price">{{ totalAmount }}</span>积分
      </div>
      <van-button
        type="danger"
        :disabled="!selectedAddress || products.length === 0 || submitting"
        :loading="submitting"
        @click="submitOrder"
      >提交订单</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showFailToast } from 'vant'
import PageHeader from '@/components/PageHeader.vue'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import { createOrder } from '@/api/order'
import { getAddressList } from '@/api/address'

const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()

// 选中的商品，确保始终使用最新数据
const products = ref<any[]>([])

// 获取购物车中选中的商品
const getCheckedItems = async (): Promise<any[]> => {
  try {
    await cartStore.refreshCartPrices()
    // 获取选中的商品
    return cartStore.cartItems.filter(item => item.checked) || []
  } catch (error) {
    console.error('获取选中商品失败:', error)
    showFailToast('获取商品信息失败')
    return []
  }
}

// 初始化商品数据
const initProducts = async () => {
  try {
    // 获取经过价格校验的商品
    const checkedItems = await getCheckedItems()
    products.value = checkedItems
  } catch (error) {
    console.error('获取商品数据失败:', error)
    showFailToast('获取商品数据失败')
    // 跳回购物车页
    router.replace('/cart')
  }
}

// 总数量
const totalQuantity = computed(() => {
  return products.value.reduce((total, item) => total + item.quantity, 0)
})

// 总积分
const totalAmount = computed(() => {
  return products.value.reduce(
    (total, item) => total + item.price * item.quantity,
    0
  )
})

// 选中的地址
const selectedAddress = ref<any>(null)
const remark = ref('')
const submitting = ref(false)

// 获取默认地址或第一个地址
const fetchDefaultAddress = async () => {
  try {
    const res = await getAddressList()
    if (res.code === 200 && res.data && res.data.length > 0) {
      // 寻找默认地址
      const defaultAddress = res.data.find((item: any) => item.isDefault)
      selectedAddress.value = defaultAddress || res.data[0]
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
  }
}

// 跳转到选择地址页面
const goToSelectAddress = () => {
  router.push('/address')
}

// 提交订单
const submitOrder = async () => {
  // 验证
  if (!selectedAddress.value) {
    showFailToast('请选择收货地址')
    return
  }

  if (products.value.length === 0) {
    showFailToast('请选择商品')
    return
  }

  // 检查积分是否足够
  if (userStore.userInfo && userStore.userInfo.points < totalAmount.value) {
    showFailToast('积分不足')
    return
  }

  submitting.value = true

  try {
    // 构造订单数据
    const orderData = {
      userId: userStore.userInfo?.id,
      items: products.value.map(item => ({
        productId: item.id,
        quantity: item.quantity,
        skuId: item.skuId,
      })),
      receiver: selectedAddress.value.name,
      phone: selectedAddress.value.phone,
      address: `${selectedAddress.value.province}${selectedAddress.value.city}${selectedAddress.value.district}${selectedAddress.value.detail}`,
      remark: remark.value,
    }

    // 发送请求
    const res = await createOrder(orderData)

    if (res.code === 200) {
      showToast({
        message: '订单创建成功',
        icon: 'success',
      })

      // 清除已购买的商品
      products.value.forEach(item => {
        cartStore.removeFromCart(item.id)
      })

      // 跳转到订单详情
      if (res.data && res.data.id) {
        router.replace(`/order/${res.data.id}`)
      } else {
        router.replace('/order')
      }
    } else {
      showFailToast(res.message || '订单创建失败')
    }
  } catch (error: any) {
    console.error('创建订单失败:', error)
    showFailToast(error.message || '创建订单失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  // 初始化数据
  initProducts()
  fetchDefaultAddress()
})
</script>

<style scoped lang="scss">
.order-create {
  min-height: 100vh;
  background-color: $background-color;
  padding-bottom: 60px;
}

.address-card {
  margin-top: $padding-xs;
  background-color: $white;
  padding: $padding-md;
  display: flex;
  position: relative;

  .address-info {
    flex: 1;

    .receiver {
      margin-bottom: $padding-xs;

      .name {
        font-size: $font-size-lg;
        font-weight: 500;
        margin-right: $padding-md;
      }

      .phone {
        color: $text-color-light;
      }
    }

    .address {
      color: $text-color;
      line-height: 1.5;
    }
  }

  .address-empty {
    flex: 1;
    display: flex;
    align-items: center;
    color: $text-color-light;
  }

  .right-icon {
    position: absolute;
    right: $padding-md;
    top: 50%;
    transform: translateY(-50%);
    color: $text-color-light;
  }
}

.product-list,
.remark-card,
.order-info {
  margin-top: $padding-xs;
  background-color: $white;
  padding: $padding-md;
}

.section-title {
  font-size: $font-size-md;
  font-weight: 500;
  margin-bottom: $padding-md;
  color: $text-color;
}

.product-item {
  display: flex;
  padding: $padding-sm 0;
  border-bottom: 1px solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }

  .product-img {
    width: 70px;
    height: 70px;
    object-fit: cover;
    border-radius: $border-radius-sm;
    margin-right: $padding-md;
  }

  .product-info {
    flex: 1;
    position: relative;

    .product-name {
      font-size: $font-size-md;
      color: $text-color;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: $padding-xs;
    }

    .product-specs {
      margin-bottom: $padding-xs;

      span {
        margin-right: $padding-xs;
      }
    }

    .product-price {
      font-size: $font-size-md;
      color: $danger-color;
    }

    .product-quantity {
      position: absolute;
      right: 0;
      bottom: 0;
      font-size: $font-size-sm;
      color: $text-color-light;
    }
  }
}

.order-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: $padding-sm;

  &:last-child {
    margin-bottom: 0;
  }

  .price {
    color: $danger-color;
    font-weight: 500;
  }
}

.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: $white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 $padding-md;
  box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.05);

  .total {
    font-size: $font-size-md;

    .price {
      color: $danger-color;
      font-weight: 500;
      font-size: $font-size-lg;
    }
  }

  .van-button {
    height: 40px;
    font-size: $font-size-md;
  }
}
</style> 